package com.tempjob.common.businesss.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.tempjob.common.utils.DateUtilsEx;
import com.tempjob.common.vo.admin.UploadFileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author hui
 * @Date 2024/1/16 上午10:55
 **/
@Slf4j
@Service
public class OssUploadService {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    @Value("${oss.endpoint:oss-cn-chengdu.aliyuncs.com}")
    private String endpoint;
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问
    @Value("${oss.accessKeyId:LTAI4GHeeFDQ8F8ibnqhkxso}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret:w9WB5oUXh4jJQTzuQJJOWdrJdAYHha}")
    private String accessKeySecret;
    @Value("${oss.bucketName:xishu-tech}")
    private String bucketName;
    @Value("${oss.host:https://oss.xishu-tech.com}")
    private String ossHost;

    public UploadFileVO upload(MultipartFile file) {
        String uploadUrl = null;
        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            //构建日期路径：avatar/2019/02/26/文件名
            String filePath = DateUtilsEx.getDay(new Date());
            //文件名：uuid.扩展名
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = filePath + "/" + newName;
            //文件上传至阿里云
            ossClient.putObject(bucketName, fileUrl, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //获取url地址
//            uploadUrl = "http://" + bucketName + "." + endpoint + "/" + fileUrl;
            uploadUrl = ossHost + "/" + fileUrl;
            return new UploadFileVO(fileUrl, uploadUrl, fileType);
        } catch (IOException e) {
            log.error("文件上传至OSS错误!", e);
        }
        return null;
    }

}
